package com.tin.triper.Helper;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.widget.Toast;

import com.tin.triper.Constants;
import com.tin.triper.R;
import com.tin.triper.Data.LocationProvider;
import com.tin.triper.Data.Trip;
import com.tin.triper.UI.TripListActivity;

public class Importing {
	public static class ImportTripFromSD extends AsyncTask<Void, Void, Boolean> {
		private ProgressDialog dialog;
		private Context context;
		public final int READ_BLOCK_SIZE = 10000;
		private String importFile;

		public ImportTripFromSD(Context context, String importFile) {
			this.context = context;
			this.importFile = importFile;
			dialog = new ProgressDialog(this.context);
		}

		protected void onPreExecute() {
			dialog.setMessage(context.getString(R.string.trip_list_importing));
			dialog.setIndeterminate(true);
			dialog.setCancelable(false);
			dialog.show();
		}

		protected Boolean doInBackground(Void... source) {
			String s = "";
			String zipFileName = importFile + ".tri";
			File sdCard = Environment.getExternalStorageDirectory();
			File backupfile = new File(sdCard.getAbsolutePath() + "/"
					+ Constants.APP_FOLDER_NAME, zipFileName);

			try {

				ZipFile file = new ZipFile(backupfile);
				ZipEntry zipentry = file.getEntry("location.bak");
				InputStream input = file.getInputStream(zipentry);

				InputStreamReader isr = new InputStreamReader(input);
				char[] inputBuffer = new char[READ_BLOCK_SIZE];

				int charRead;
				while ((charRead = isr.read(inputBuffer)) > 0) {
					String readString = String.copyValueOf(inputBuffer, 0,
							charRead);
					s += readString;
					inputBuffer = new char[READ_BLOCK_SIZE];
				}
			} catch (Exception e) {
				e.printStackTrace();
				return false;
			} 
			JSONObject jobject;
			try {
				Trip trip = new Trip();
				jobject = new JSONArray(s).getJSONObject(2);
				JSONArray jarray = new JSONArray(jobject.getString("trip"));

				for (int i = 0; i < jarray.length(); i++) {
					JSONObject job = jarray.getJSONObject(i);
					Cursor cursor = context.getContentResolver().query(
							LocationProvider.CONTENT_URI_TRIPS,
							new String[] { LocationProvider.TRIP_ID },
							LocationProvider.TRIP_NAME + " ='"
									+ job.getString("name") + "' AND "+LocationProvider.TRIP_TIME+"= '"+job.getString("time")+"'", null, null);
					if (cursor.getCount() > 0) {
						cursor.close();
						return false;
					}
					cursor.close();
					trip.tripName = job.getString("name");
					
					ContentValues values = new ContentValues();
					values.put(LocationProvider.TRIP_LENGTH,
							job.getString("length"));
					values.put(LocationProvider.TRIP_NAME,
							job.getString("name"));
					values.put(LocationProvider.TRIP_TIME,
							job.getString("time"));
					context.getContentResolver().insert(
							LocationProvider.CONTENT_URI_TRIPS, values);
					cursor = context.getContentResolver().query(
							LocationProvider.CONTENT_URI_TRIPS,
							new String[] { LocationProvider.TRIP_ID },
							LocationProvider.TRIP_NAME + " ='"
									+ job.getString("name") + "' AND "+LocationProvider.TRIP_TIME+"= '"+job.getString("time")+"'", null, null);
					if (cursor.moveToFirst())
						trip.tripId = cursor.getInt(0);
					cursor.close();

				}
				ArrayList<LocationId> locationList = new ArrayList<LocationId>();
				jobject = new JSONArray(s).getJSONObject(0);
				jarray = new JSONArray(jobject.getString("locations"));
				for (int i = 0; i < jarray.length(); i++) {
					JSONObject job = jarray.getJSONObject(i);
					LocationId location = new LocationId();
					location.oldId = job.getInt("id");
					ContentValues values = new ContentValues();
					values.put(LocationProvider.LOCATION_LATITUDE,
							job.getString("location_lat"));
					values.put(LocationProvider.LOCATION_TIME,
							job.getString("location_time"));
					values.put(LocationProvider.LOCATION_LONGITUDE,
							job.getString("location_long"));
					values.put(LocationProvider.TRIP_ID, trip.tripId);
					context.getContentResolver().insert(
							LocationProvider.CONTENT_URI_LOCATION, values);
					Cursor cursor = context.getContentResolver().query(
							LocationProvider.CONTENT_URI_LOCATION,
							new String[] { LocationProvider.LOCATION_ID },
							LocationProvider.LOCATION_TIME + " ='"
									+ job.getString("location_time") + "'",
							null, null);
					if (cursor.moveToFirst())
						location.newId = cursor.getInt(0);
					cursor.close();
					locationList.add(location);
				}
				jobject = new JSONArray(s).getJSONObject(1);
				jarray = new JSONArray(jobject.getString("resources"));
				for (int i = 0; i < jarray.length(); i++) {
					JSONObject job = jarray.getJSONObject(i);
					ContentValues values = new ContentValues();
					values.put(LocationProvider.RESOURCE_FILENAME,
							job.getString("filename"));
					values.put(LocationProvider.RESOURCE_TYPE,
							job.getString("type"));
					values.put(LocationProvider.RESOURCE_DESCRIPTION,
							job.getString("description"));
					values.put(LocationProvider.TRIP_ID, trip.tripId);
					for (int l = 0; l < locationList.size(); l++) {
						if (job.getInt("location_id") == locationList.get(l).oldId)
							values.put(LocationProvider.LOCATION_ID,
									locationList.get(l).newId);
					}
					if (!job.getString("filename").equals("")) {
						ZipFile file = new ZipFile(backupfile);
						String temp = "";
						switch (job.getInt("type")) {
						case 1:
							temp += "Voice";
							break;
						case 2:
							temp += "Image";
							break;
						case 3:
							temp += "Video";
							break;
						default:
							break;
						}
						ZipEntry zipentry = file.getEntry(temp+"/"+job
								.getString("filename"));
						InputStream input = file.getInputStream(zipentry);
						File mediaStorageDir = new File(Environment
								.getExternalStorageDirectory()
								.getAbsolutePath()
								+ "/"
								+ Constants.APP_FOLDER_NAME
								+ "/"
								+ trip.tripId + " " + trip.tripName+"/" + temp);
						if (!mediaStorageDir.exists()) {
							if (!mediaStorageDir.mkdirs()) {
								return false;
							}
						}
						File toSaveFile = new File(mediaStorageDir, job.getString("filename"));
						FileOutputStream fOut = new FileOutputStream(toSaveFile);
						byte[] buffer = new byte[1024];
						int length;
						try {
							while ((length = input.read(buffer)) > 0) {
								fOut.write(buffer, 0, length);
							}
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
					context.getContentResolver().insert(
							LocationProvider.CONTENT_URI_RESOURCES, values);
				}

			} catch (Exception e) {
				e.printStackTrace();
				return false;
			}

			return true;
		}

		protected void onProgressUpdate(Void... progress) {
		}

		protected void onPostExecute(Boolean result) {
			if (dialog.isShowing())
				dialog.dismiss();
			if (result){
				Toast.makeText(context,
						context.getString(R.string.importing_export_success),
						Toast.LENGTH_SHORT).show();
			}
			else
			{
				Toast.makeText(context,
						context.getString(R.string.importing_export_failed),
						Toast.LENGTH_SHORT).show();
			}
		}
	}

	private static class LocationId {
		int oldId;
		int newId;
	}
}
